/**
 * 
 */
package org.xelnaga.defiler.web.controller;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.xelnaga.defiler.domain.OrderItemModel;
import org.xelnaga.defiler.domain.OrderModel;

/**
 * @author qijb
 *
 */
public class OrderForm {
	private OrderModel order = new OrderModel();
	private final Map<Long, OrderItemModel> itemMap = 
		Collections.synchronizedMap(new HashMap<Long, OrderItemModel>());

	/**
	 * 
	 */
	public OrderForm() {
		// TODO Auto-generated constructor stub
	}
	public OrderModel getOrder() {
		return order;
	}
	public void setOrder(OrderModel order) {
		this.order = order;
	}
	public Collection<OrderItemModel> getOrderItemList() {
		return itemMap.values();
	}


	public void addOrderItem(OrderItemModel orderItem) {
		OrderItemModel cartItem = itemMap.get(orderItem.getContentletInode());
	    if (cartItem == null) {//Item not exist
	    	orderItem.setItemNum(itemMap.size() + 1);
	    	itemMap.put(orderItem.getContentletInode(), orderItem);
	    	//Need caculate current item price.
	    	orderItem.caculateTotalPrice();
	    } else {//item existed
	    	cartItem.incrementQuantity(orderItem.getQuantity());
	    }
	}
	
	public void decreaseOrderItemQuantity(OrderItemModel orderItem) {
		OrderItemModel cartItem = itemMap.get(orderItem.getContentletInode());
		if(null != cartItem) {
			cartItem.decreaseQuantity(orderItem.getQuantity());
		} else {
			this.addOrderItem(orderItem);
		}
	}

	public double getOrderTotalPrice() {
		//caculdate all order item price
		double result = getOrderTotalMarketPrice() + 
			(order.getShipping() == null ? 0 : order.getShipping());
		order.setTotalPrice(result);
		return result;
	}
	
	public double getOrderTotalMarketPrice() {
		double result = 0;
		for(OrderItemModel model : this.itemMap.values()) {
			double current = model.caculateTotalPrice();//model.getPrice() * model.getQuantity();
			result += current;
		}
		return result;
	}
	
	public double getOrderSavingsPrice() {
		return getOrderTotalMarketPrice() - this.getOrderTotalPrice();
	}
	
	public double getOrderSavingsDiscount() {
		if(getOrderSavingsPrice() > 0) {
			return Math.round(getOrderSavingsPrice() / this.getOrderTotalMarketPrice());
		}
		return 0;
	}
	
	public void updateCartQuantity(Long contentletInode, Integer quantity) {
		OrderItemModel cartItem = itemMap.get(contentletInode);
	    if (cartItem == null) {//Item not exist
	    	cartItem = new OrderItemModel();
	    	cartItem.setItemNum(itemMap.size() + 1);
	    	itemMap.put(contentletInode, cartItem);
	    	//Need caculate current item price.
	    	cartItem.caculateTotalPrice();
	    } else {//item existed
	    	cartItem.setQuantity(quantity);
	    }
	}
	public void deleteCartItems(Long contentletInode) {
		if(itemMap.containsKey(contentletInode)) {
			itemMap.remove(contentletInode);
		}
	}
}
